package com.hertz.alarm.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.hertz.alarm.dao.EhCacheDao;
import com.hertz.alarm.entity.IrisUser;
import com.hertz.alarm.service.EntityService;
import com.hertz.alarm.service.IrisUserService;
import com.hertz.alarm.util.Constants4Ehcache;
import com.hertz.alarm.util.StringUtils;
@Service
public class IrisUserServiceImpl extends BaseServiceImpl implements
		IrisUserService {
	@Resource
	private EntityService entityService;
	@Resource
	private EhCacheDao ehcacheDao;
	
	@Override
	public IrisUser getByToken(String token) {
		IrisUser irisUser = (IrisUser)ehcacheDao.get(String.format(Constants4Ehcache.KEY_USER_TOKEN, token), Constants4Ehcache.REGION_USER);
		if(irisUser == null){
			irisUser = baseDAO.getUniqueResult(IrisUser.GET_BY_TOKEN, token);
			if(irisUser != null)
				ehcacheDao.save(String.format(Constants4Ehcache.KEY_USER_TOKEN, token),irisUser, Constants4Ehcache.REGION_USER);
		}
		return irisUser;
	}

	@Override
	public IrisUser getUser(String name, String site) {
		IrisUser irisUser = baseDAO.getUniqueResult(IrisUser.GET_FROM_SSO, name,site);
		return irisUser;
	}

	@Override
	public IrisUser getOrCreateUser(String name, String site) {
		IrisUser irisUser = getUser(name,site);
		if(irisUser == null){
			irisUser = createUser(name, site);
		}
		return irisUser;
	}

	@Override
	public IrisUser createUser(String name, String site) {
		IrisUser irisUser = new IrisUser();
		long time = System.currentTimeMillis();
		irisUser.setCtime(time);
		irisUser.setLastLogin(time);
		irisUser.setSsoSite(site);
		irisUser.setSsoUsername(name);
		irisUser.setSsoToken(StringUtils.getMD5Str(site+name+time));
		entityService.save(irisUser);
		ehcacheDao.save(String.format(Constants4Ehcache.KEY_USER_TOKEN, irisUser.getSsoToken()),irisUser, Constants4Ehcache.REGION_USER);
		return irisUser;
	}
	
}
